package com.proyectofinal.ramas.service;

import com.proyectofinal.ramas.domain.UserRole;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class CustomUserService implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException {

        com.proyectofinal.ramas.domain.User domainUser = userService.get(userName);
        List<UserRole> domainUserRoles = userRoleService.getAll(domainUser);
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        return new UserImpl(
                domainUser.getUserName(),
                domainUser.getPassword(),
                enabled,
                accountNonExpired,
                credentialsNonExpired,
                accountNonLocked,
                getAuthorities(domainUserRoles),
                null);
    }

    public Collection getAuthorities(List<UserRole> roles) {
        List authList = getGrantedAuthorities(getRoles(roles));
        return authList;
    }

    public List<String> getRoles(List<UserRole> roles) {

        List<String> authoritiesRoles = new ArrayList<String>();
        for (UserRole role : roles) {
            if (role.getUserRolePK().getRole().getRoleID() == 1) {
                authoritiesRoles.add("ROLE_ADMIN");
            } else if (role.getUserRolePK().getRole().getRoleID() == 2) {
                authoritiesRoles.add("ROLE_CLIENT");
            }

        }


        return authoritiesRoles;
    }

    public static List getGrantedAuthorities(List<String> roles) {
        List authorities = new ArrayList();

        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }
}
